package com.aat.dxfy.http.login;

import java.io.IOException;
import java.util.*;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class LoginFormDemo {

	public static void main(String[] args) throws IOException {
		session();
		
		login();
		
		session();
		
		signout();
		
		session();
	}

	public static void login()  throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//
		HttpPost httpPost = new HttpPost("http://127.0.0.1:56789/api/account/signin");

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("name", "admin"));
		nvps.add(new BasicNameValuePair("password", "admin"));
		nvps.add(new BasicNameValuePair("remember", "0"));

		httpPost.setEntity(new UrlEncodedFormEntity(nvps));

		CloseableHttpResponse response = httpClient.execute(httpPost);

		System.out.println(response.getStatusLine());

		HttpEntity responseEntity = response.getEntity();

		String res = EntityUtils.toString(responseEntity, "UTF-8");

		System.out.println("login:\n\t"+res);

		EntityUtils.consume(responseEntity);

		response.close();

		//
		httpClient.close();
	}
	
	public static void session()  throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//
		HttpGet httpGet = new HttpGet("http://127.0.0.1:56789/api/account/session");

		CloseableHttpResponse response = httpClient.execute(httpGet);

		System.out.println(response.getStatusLine());

		HttpEntity responseEntity = response.getEntity();

		String res = EntityUtils.toString(responseEntity, "UTF-8");

		System.out.println("session:\n\t"+res);

		EntityUtils.consume(responseEntity);

		response.close();

		//
		httpClient.close();
	}
	
	public static void signout()  throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//
		HttpGet httpGet = new HttpGet("http://127.0.0.1:56789/api/account/signout");

		CloseableHttpResponse response = httpClient.execute(httpGet);

		System.out.println(response.getStatusLine());

		HttpEntity responseEntity = response.getEntity();

		String res = EntityUtils.toString(responseEntity, "UTF-8");

		System.out.println("signout:\n\t"+res);

		EntityUtils.consume(responseEntity);

		response.close();

		//
		httpClient.close();
	}

}